<template>
	<view>
		<u-navbar title="积分管理" :border="border" leftIconSize="0" :bgColor="bgColor" :titleStyle="{color: color}">
		</u-navbar>
		<template v-if="!loading">
			<!-- 轮播图 -->
			<u-swiper @click="swiperClick" imgMode="scaleToFill" height="220" :list="bannerList" indicator indicatorMode="line" circular />
			<!-- 公告通知 -->
			<u-notice-bar fontSize="16"  :speed="40" bgColor="#f5f5f5" color="#e1251b" :text="notice" />
			<!-- 积分 -->
			<u-sticky bgColor="#fff" :customNavHeight="customNavHeight">
				<view class="points-box">
					<!-- 积分 -->
					<view class="points-num" @tap="toPage({url: '/pages/index/points_record'})">
						<u--image :showLoading="true"
							src="/static/image/home/1.png"
							shape="circle" width="32px" height="32px"></u--image>
						<text class="points-num-1">{{userInfo.totalPoints || 0}}</text>
					</view>
					<!-- 赚积分 -->
					<view class="points-get" @tap="toPage({url: '/pages/index/points_record'})">
						<u--image :showLoading="true"
							src="/static/image/home/2.png"
							shape="circle" width="34px" height="34px"></u--image>
						<text class="points-num-1">积分明细</text>
					</view>
				</view>
				<view style="height: 8rpx;background-color: #f5f5f5;"></view>
				<view class="home-class">
					<view @tap="changeActive(index)" v-for="(item, index) in list1" :key="index">
						<text :class="{active: index === activeIndex}">{{item.name}}</text>
					</view>
				</view>
			</u-sticky>
			<!-- 如何赚积分 -->
			<!-- <u--image :showLoading="true" :src="src" width="100%" height="80px" /> -->

			<!-- 商品 -->
			<view>
				<view class="waterfall-box h-flex-x h-flex-2">
					<view>
						<HelangWaterfall v-for="(item,index) in leftList" :key="index" :params="item" tag="left"
							:index="index" @height="onHeight" @click="onClick"></HelangWaterfall>
					</view>
					<view>
						<HelangWaterfall v-for="(item,index) in rightList" :key="index" :params="item"
							@height="onHeight" @click="onClick" tag="right" :index="index"></HelangWaterfall>
					</view>
				</view>
				<u-empty
						v-if="leftList.length===0 && rightList.length===0"
						text=" "
				        mode="data"
				        icon="http://cdn.uviewui.com/uview/empty/data.png"
				>
				</u-empty>
				<u-loadmore loadingIcon="semicircle" iconColor="#f12312" :status="status" />
			</view>
		</template>
		<u-loading-page loading-color="#e1251b" color="#e1251b" :loadingText="loadingText" :loading="loading" loading-mode="semicircle" loadingText="积分管理"></u-loading-page>
		<u-back-top :scroll-top="scrollTop"></u-back-top>
	</view>
</template>

<script>
	import {userQueryById, propertyPointBanner, propertyPointNotice, propertyPointGoodsInfo} from '@/api/home.js';
	import GoodsItem from '@/components/goods-item.vue';
	import HelangWaterfall from '@/components/helang-waterfall.vue';
	import {mapState, mapActions} from 'vuex';
	export default {
		name: 'index',
		components: {
			GoodsItem,
			HelangWaterfall
		},
		data() {
			return {
				activeIndex: 0,
				list1: [{
					name: '精选'
				}, {
					name: '新品'
				}, {
					name: '积分'
				}, {
					name: '线下'
				}],
				bannerList: [],
				notice: '',
				src: 'https://cdn.uviewui.com/uview/album/1.jpg',
				leftHeight: 0,
				rightHeight: 0,
				leftList: [],
				rightList: [],
				ajax: {
					// 是否可以加载
					load: true,
					// 加载中提示文字
					loadTxt: '',
					// 每页的请求条件
					rows: 6,
					// 页码
					page: 1,
				},
				status: 'loadmore',
				loading: true,
				scrollTop: 0,
				loadingText: '',
				color: 'transparent',
				bgColor: 'transparent',
				border: false
			}
		},
		computed: {
			...mapState(['userInfo']),
			customNavHeight() {
				return this.statusBarHeight + 44 + 'px';
			}
		},
		onReady() {
			// 获取轮播图
			propertyPointBanner().then(res => {
				let bannerList = []
				res.result.forEach(item => {
					bannerList.push(item.image)
				})
				this.bannerList = bannerList;
			})
			// 获取公告
			propertyPointNotice().then(res => {
				const {title, content} = res.result;
				this.notice = `${title}: ${content}`
			})
			
			this.getList();
		},
		// 触底触发
		onReachBottom() {
			this.getList();
		},
		onShow() {
			let {id} = this.userInfo;
			if(id) {
				userQueryById({id}).then(res => {
					this.setUserInfo({userInfo: res.result})
				})
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.resetData();
		},
		onPageScroll(e) {
			if (e.scrollTop > 100) {
				this.color = '#000';
				this.bgColor = '#fff';
				this.border = true;
			} else {
				this.color = 'transparent';
				this.bgColor = 'transparent';
				this.border = false;
			}
			this.scrollTop = e.scrollTop;
		},
		methods: {
			...mapActions(['setUserInfo']),
			swiperClick(index) {
				this.previewImg(index, this.bannerList)
			},
			// 预览图片
			previewImg(current, urls) {
				uni.previewImage({
					current,
					urls,
				});
			},
			// 去往新页面
			toPage({url}) {
				this.$cuNavigateTo(url);
			},
			resetData() {
				this.ajax.page = 1;
				this.leftHeight = 0;
				this.rightHeight = 0;
				this.ajax.load = true;
				this.leftList = [];
				this.rightList = [];
				this.getList();
			},
			// 改变当前选中
			changeActive(index) {
				this.activeIndex = index;
				this.resetData();
			},
			// 监听高度变化
			onHeight(height, tag) {
				if (tag == 'left') {
					this.leftHeight += height;
				} else {
					this.rightHeight += height;
				}
			},
			// 组件点击事件
			onClick(index, tag) {
				let id = null
				// 对应的数据
				if (tag == 'left') {
					id = this.leftList[index].id
					console.log();
				} else {
					id = this.rightList[index].id
				}
				let direction = {
					"left": '左',
					"right": '右'
				}
				uni.navigateTo({
					url: `/pages/index/goods_detail?id=${id}`
				})
			},
			// 获取数据
			getList() {
				/* 
					无真实数据，当前由 setTimeout 模拟异步请求、
					自行替换 请求方法将数据 传入 addList() 方法中
					自行解决数据格式，自行修改组件内布局和内容绑定
				*/
				if (!this.ajax.load) {
					return;
				}
				this.status = 'loading';
				propertyPointGoodsInfo({pageNo: this.ajax.page, pageSize: this.ajax.rows, goodsType: this.activeIndex+1}).then(res => {
					const {current, pages, records} = res.result;
					if(current >= pages) {
						this.ajax.load = false;
						this.status = 'nomore';
					} else {
						this.ajax.load = true;
						this.status = 'loading';
						// this.ajax.loadTxt = '上拉加载更多';
						this.ajax.page++;
					}
					uni.stopPullDownRefresh()
					this.loading = false;
					this.addList(records);
				})
			},
			addList(res) {
				// // 获取到的数据，请注意数据结构
				// if (!this.ajax.load) {
				// 	this.status = 'nomore'
				// 	// this.ajax.loadTxt = '没有更多了';
				// 	return;
				// }

				// 左右列表高度的差
				let differ = this.leftHeight - this.rightHeight;
				// 计算差值，用于确定优先插入那一边
				let differVal = 0;

				// 初始化左右列表的数据
				let i = differ > 0 ? 1 : 0;

				let [left, right] = [
					[],
					[]
				];


				// 获取插入的方向
				let getDirection = (index) => {
					/* 左侧高度大于右侧超过 600px 时，则前3条数据都插入到右边 */
					if (differ >= 600 && index < 3) {
						differVal = 1;
						return 'right';
					}

					/* 右侧高度大于左侧超过 600px 时，则前3条数据都插入到左边 */
					if (differ <= -600 && index < 3) {
						differVal = -1;
						return 'left';
					}

					/* 左侧高度大于右侧超过 350px 时，则前2条数据都插入到右边 */
					if (differ >= 350 && index < 2) {
						return 'right';
					}
					/* 右侧高度大于左侧超过 350px 时，则前2条数据都插入到左边 */
					if (differ <= -350 && index < 2) {
						differVal = -1;
						return 'left';
					}

					/* 当前数据序号为偶数时，则插入到左边 */
					if ((i + differVal) % 2 == 0) {
						return 'left';
					} else {
						/* 当前数据序号为奇数时，则插入到右边 */
						return 'right';
					}
				}

				// 将数据源分为左右两个列表，容错差值请自行根据项目中的数据情况调节
				res.forEach((item, index) => {
					if (getDirection(index) == 'left') {
						//console.log(`差值：${differ},方向：left，序号${index}`)
						left.push(item);
					} else {
						//console.log(`差值：${differ},方向：right，序号${index}`)
						right.push(item);
					}
					i++;
				});

				// 将左右列表的数据插入，第一页时则覆盖
				if (this.ajax.page == 1) {
					this.leftList = left;
					this.rightList = right;
					uni.stopPullDownRefresh();
				} else {
					this.leftList = [...this.leftList, ...left];
					this.rightList = [...this.rightList, ...right];
				}
			}
		}
	}
</script>

<style>
	page {
		background-color: #f5f5f5;
	}
	.u-notice-bar {
		padding: 12px 12px!important;
	}
</style>
<style lang="scss" scoped>
	
	.points-box {
		display: flex;
		align-items: center;
		height: 100rpx;
		.points-num,
		.points-get {
			flex: 1;
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.points-num-1 {
				padding-left: 16rpx;
				font-size: 32rpx;
				color: #000;
			}
		}
	}

	.waterfall-box {
		padding: 16rpx 8rpx;
		box-sizing: border-box;

		>view {
			padding: 0 8rpx;
		}
	}

	.h-flex-x {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: flex-start;
		align-content: flex-start;

		&.h-flex-2 {
			>view {
				width: 50%;
			}
		}
	}

	.load-txt {
		padding: 0 0 20rpx 0;
		text-align: center;
		color: #999;
		font-size: 24rpx;
	}
	
	.home-class {
		height: 100rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		color: #333;
		font-size: 32rpx;
		view {
			height: 100%;
			flex: 1;
			text-align: center;
			line-height: 100rpx;
		}
	}
	.active {
		font-weight: bold;
		position: relative;
		&::after {
			content: '';
			display: block;
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			bottom: -8rpx;
			height: 4rpx;
			border-radius: 2rpx;
			width: 44rpx;
			background-color: $uni-color-primary;
		}
	}
</style>
